package net.zhengxinyun.performance.controller.indicators;


import com.sirdc.modules.core.exceptions.SystemException;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;

import net.zhengxinyun.performance.App.dto.IndexUserDTO;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.Util.WordUtil;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.dto.HistoryScoreDTO;
import net.zhengxinyun.performance.dto.TownDTO;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.DepartmentFilter;
import net.zhengxinyun.performance.filter.TownFilter;
import net.zhengxinyun.performance.filter.TownIndicatorsFilter;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.exportService.ExportExccelServiceImpl;
import net.zhengxinyun.performance.service.exportService.ExportService;
import net.zhengxinyun.performance.service.indicators.TownIndicatorsService;
import net.zhengxinyun.performance.service.indicators.TownScoreService;
import net.zhengxinyun.performance.service.indicators.TownService;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.RolePerService;
import net.zhengxinyun.performance.service.login.TokenService;
import net.zhengxinyun.performance.service.login.UserService;
import net.zhengxinyun.performance.service.report.IndexReportService;
import net.zhengxinyun.performance.service.setTime.SetTimeService;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 县对乡镇指标考核
 */
@RestController
@RequestMapping("/townScore")
public class TownScoreController {

    private TownIndicatorsService townIndicatorsService;
    private TownService townService;
    private TokenService tokenService;
    private TownScoreService townScoreService;
    private UserService userService;
    private LoginService loginService;
    private ExportService exportExcel;
    private SetTimeService setTimeService;
    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private IndexReportService reportService;


    @Autowired
    private RolePerService rolePerService ;

    Logger logger = LoggerFactory.getLogger(TownScoreController.class);

    @Autowired
    public TownScoreController(TownIndicatorsService townIndicatorsService, TownService townService, TokenService tokenService,
                               TownScoreService townScoreService, UserService userService,
                               LoginService loginService, ExportService exportExcel, SetTimeService setTimeService) {
        this.townIndicatorsService = townIndicatorsService;
        this.townService = townService;
        this.tokenService = tokenService;
        this.townScoreService = townScoreService;
        this.userService = userService;
        this.loginService = loginService;
        this.exportExcel = exportExcel;
        this.setTimeService = setTimeService;
    }




    @PostMapping("/query")
    public Result<HashMap<String,Object>> queryScore(@RequestBody TownIndicatorsParam param, HttpServletRequest request){
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            Double pageTotal = 0.0;
            //返回一级指标和对应的二级指标
            HashMap<String,Object> map = new HashMap<>();
            TownIndicatorsFilter townIndicatorsFilter = new TownIndicatorsFilter();
            /**
             * 用户
             */
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            /**
             * 角色
             */
            RolePerEntity userRole = rolePerService.selectByPrimaryKey(userEntity.getRoleid());
            /**
             * 部门
             */
            DepartmentEntity departmentEntity = departmentService.selectByCode(userEntity.getDepartcode());
            /*
             *  县对乡镇指标
             * 权限筛选 超级管理员和乡镇用户可以看全部指标、县直单位只能看自己牵头的指标。
             * 判断是否是超级管理或者是否县直单位。
             *
           /* if (!"admin".equals(userEntity.getUserPermissions()) && "县直单位".equals(departmentEntity.getDepartType().trim() ) ){
                param.townIndicatorsFilter.setLeadUnit(userEntity.getDepartcode());
            }*/
            townIndicatorsFilter.setIndexType("一级指标");
            List<TownIndicatorsFilter> firstIndexList = townIndicatorsService.query(townIndicatorsFilter);
            List<Map<String,Object>> indexList = townIndicatorsService.queryIndexMap(firstIndexList);
            map.put("indexMap",indexList);

            /**
             * 搜索条件为空，默认取最新
             */
            if(StringUtils.isBlank(param.townIndicatorsFilter.getDateTime())){
               // String datetime  =(String) request.getSession().getAttribute("currentYear");
                SetTimeEntity year= setTimeService.findByIndexClass("3");
                param.townIndicatorsFilter.setDateTime(year.getStartTime());
            }



           /**
            *-------查询出结果集合-------
            * */
            List<Map<String, Object>> list = townScoreService.query(param.townIndicatorsFilter,userRole,userEntity);
            if (list.size() == 0){
                param.townIndicatorsFilter.setPageNumber(param.townIndicatorsFilter.getPageNumber()-1);
                list = townScoreService.query(param.townIndicatorsFilter,userRole,userEntity);
            }
            String notic ="";
            try {
                //判断当前时间是否可填写分数

                SetTimeEntity setTimeEntity = setTimeService.findByIndexClass("1");
                String startTime = setTimeEntity.getStartTime();
                String endTime = setTimeEntity.getEndTime();

                int start = Integer.parseInt(startTime);
                int end = Integer.parseInt(endTime);
                Date date = new Date();
                //获取当前日
                int date1 = date.getDate();
                if ("1".equals(setTimeEntity.getIsThisMonth())){
                    if (date1>=start&&date1<=end){
                        map.put("status", "1");
                    }else{
                        map.put("status", "0");
                    }
                    notic="指标数据填写时限：请在当月"+start+"号至当月"+end+"号完成指标数据的填报！！！";

                }
                if ("2".equals(setTimeEntity.getIsThisMonth())){
                    if (date1>=start||date1<=end) {
                        map.put("status", "1");
                    }else {
                        map.put("status", "0");
                    }
                    notic="指标数据填写时限：请在当月"+start+"号至次月"+end+"号完成指标数据的填报！！！";
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            map.put("notice",notic);
            map.put("list", list);
           // pageTotal = townIndicatorsService.queryForCount(param.townIndicatorsFilter);
            param.townIndicatorsFilter.setIndexType("二级指标");
            param.townIndicatorsFilter.setDateTime(null);
           pageTotal = Util.intGetTotalPage(   townIndicatorsService.queryForCount(param.townIndicatorsFilter),param.townIndicatorsFilter.getPageSize());
            map.put("pageTotal",pageTotal);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME,"token不对",null);
    }

    /**
     * 审核页面查询
     * @param param
     * @return
     */
    @PostMapping("/queryForAudit")
    public Result<HashMap<String,Object>> queryScoreForAudit(@RequestBody TownIndicatorsParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            Double pageTotal = 0.0;
            //返回一级指标和对应的二级指标
            HashMap<String,Object> map = new HashMap<>();
            TownIndicatorsFilter townIndicatorsFilter = new TownIndicatorsFilter();
            townIndicatorsFilter.setIndexType("一级指标");
            List<TownIndicatorsFilter> firstIndexList = townIndicatorsService.query(townIndicatorsFilter);
            List<Map<String,Object>> indexList = townIndicatorsService.queryIndexMap(firstIndexList);
            map.put("indexMap",indexList);
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            if (!"admin".equals(userEntity.getUserPermissions())){
                param.townIndicatorsFilter.setMainUnit(userEntity.getUserDepartment());
            }
            //三个表关联查询出结果
            List<Map<String, Object>> list = townScoreService.queryForAudit(param.townIndicatorsFilter);
            if (list.size() == 0){
                param.townIndicatorsFilter.setPageNumber(param.townIndicatorsFilter.getPageNumber()-1);
                list = townScoreService.queryForAudit(param.townIndicatorsFilter);
            }
            map.put("list", list);
            pageTotal = Util.intGetTotalPage(townScoreService.getAuditCount(param.townIndicatorsFilter),param.townIndicatorsFilter.getPageSize());
            map.put("pageTotal",pageTotal);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME,"token不对",null);
    }

    /**
     * 设置个乡镇分数
     * townIndicatorsFilter 接收对应指标id等
     * townList 接收对应乡镇分数排名等
     * @param param
     * @return
     */
    @PostMapping("/setScore")
    public Result<String> setScore(@RequestBody TownScoreParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())){
           String str = townScoreService.setScore(param.townIndicatorsFilter,param.list);
            if (!"操作成功".equals(str)){
                return ResultUtils.getResults(Result.Status.ERROR,str);
            }else {
                return ResultUtils.getSuccessResults();
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME,"token不对",null);
    }

    @PostMapping("/pass")
    public Result<String> pass(@RequestBody TownScoreParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            String str ;
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            //判断角色权限
            if ("admin".equals(userEntity.getUserPermissions())) {
                str = townScoreService.auditAllPass(param.list);
                if (!"操作成功".equals(str)){
                    return ResultUtils.getResults(Result.Status.ERROR,str);
                }else {
                    for (TownIndicatorsFilter townIndicatorsFilter:param.list) {
                        String s = townScoreService.setFirstFinalScore(townIndicatorsFilter);
                        if (!"操作成功".equals(s)){
                            return ResultUtils.getResults(Result.Status.ERROR,s);
                        }
                    }
                    return ResultUtils.getSuccessResults();
                }
            }else if ("responsible".equals(userEntity.getUserPermissions())){
                str = townScoreService.responsibleAllPass(param.list);
                if (!"操作成功".equals(str)){
                    return ResultUtils.getResults(Result.Status.ERROR,str);
                }else {
                    return ResultUtils.getSuccessResults();
                }
            }else {
                return ResultUtils.getResults(Result.Status.ERROR, "对不起，当前账号无审核权限");
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME,"token不对",null);
    }

    /**
     * 回退
     * @param param
     * @return
     */
    @PostMapping("/noPass")
    public Result<String> noPass(@RequestBody TownScoreParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            String str = townScoreService.noPass(param.townIndicatorsFilter);
            if (!"操作成功".equals(str)){
                return ResultUtils.getResults(Result.Status.ERROR,str);
            }else {
                return ResultUtils.getSuccessResults();
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME,"token不对",null);
    }

    @PostMapping("/importTownScore")
    public Result<String> importTownScore(@RequestParam(value = "file") MultipartFile file){
        String str = townScoreService.importTownScore(file);
        if (!"导入成功".equals(str)){
            return ResultUtils.getResults(Result.Status.ERROR,str);
        }
        return ResultUtils.getSuccessResults();
    }

    /*
        ----------------下载模板-----------------
        fileName参数一定要穿， 中文名可传可不穿。
     */

    /**
     *
     * @param response
     * @param fileName
     * @param chinaName
     * @throws IOException
     */
    @GetMapping("/downTownScoreMoudle")
    public void downloadScoreModel(HttpServletResponse response,String fileName,String chinaName) throws IOException {
     /* String temple=  ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/";
      //temple= temple+"mould/scoreMoudle.xlsx";
        temple= temple+"mould/"+fileName;

        logger.info("== "+temple+" ==");*/

      //  String path  = ResourceUtils.getURL("classpath:").getPath()+"static/mould/"+fileName;
        String path ="/static/mould/"+fileName;
        ClassPathResource resource  = new ClassPathResource(path);


        ServletOutputStream out  = null;
        InputStream ips =null;
        try {

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-msdownload");
            String filename = chinaName;
            if(StringUtils.isBlank(chinaName)){
                filename="导入模板.xlsx";
            }

            response.setHeader("Content-Disposition","attachment;filename=".concat(String.valueOf(URLEncoder.encode(filename,"UTF-8")))  );
           InputStream inputStream = resource.getInputStream();
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            inputStream.close();
            outputStream.close();
           /* out = response.getOutputStream();
            byte[] buffer = new byte[512];
            int b = -1;
            while ((b= ips.read(buffer)) !=-1)
            {
                out.write(buffer,0,b);
            }*/

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(ips != null)
                    ips.close();

            if(out!=null)
                out.close();

        }

    }

    /**
     *-----------导入指标分数 县对乡镇分数---
     * @param param
     * @return
     */
    @PostMapping("/importIndictScore")
    public Result<String> importscore(@RequestBody TownScoreParam param)
    {
        String dateTime = param.townIndicatorsFilter.getDateTime();

        if(ObjectUtils.isNotBlank(dateTime ))
        {
            if("1".equals(dateTime)){
                dateTime = DateUtils.getCurrentMonth();
            }else {
                dateTime= DateUtils.getLastMonth();
            }
        }else {
            return  ResultUtils.getResults(Result.Status.ERROR,"请先选择日期");
        }
        /**
         * 获取当前登录用户
         */
        UserEntity user = loginService.getUserByToken(param.tokenEntity);

        if(ObjectUtils.isBlank(param.townIndicatorsFilter.getTownList()) )
        {
            return ResultUtils.getResults(Result.Status.ERROR,"数据为空，请重新导入");
        }




       List<TownEntity> list = param.townIndicatorsFilter.getTownList();
        for(TownEntity town: list)
        {
            if(StringUtils.isBlank(town.getScore())||"-".equals(town.getScore()))
            {
                if(StringUtils.isNotBlank(town.getScore()))
                    town.setScore( town.getScore().replace("-","") );
                continue;
            }
            Double score;
            try {
                score = Double.parseDouble(town.getScore());
            }catch (NumberFormatException e)
            {
                //town.getTownName()+town.getScore();
                return ResultUtils.getResults(Result.Status.ERROR,"数据格式，请输入纯数字或者小数,不包含其他字符。错误数据为："+ town.getTownName()+":"+town.getScore()+" ;请重新导入");
            }


            town.setSocreRate( score.doubleValue());

        }

        Collections.sort(list, new Comparator<TownEntity>() {
            @Override
            public int compare(TownEntity o1, TownEntity o2) {
                return -Double.compare(o1.getSocreRate(),o2.getSocreRate());
            }
        });




        townScoreService.importScore(list,param.townIndicatorsFilter.getId(), user,dateTime);
        //保存到报送表
        reportService.saveReport(user,2,param.townIndicatorsFilter.getId(),dateTime );
        return  ResultUtils.getSuccessResults();
    }

    /**
     * ------导入后分数查询。
     * @param param
     * @return
     */
    @PostMapping("/afterimport")
    public Result<HashMap<String,Object>> afterimport(@RequestBody TownScoreParam param)
    {

        String datetime =param.townIndicatorsFilter.getDateTime();
        if(StringUtils.isNotBlank(datetime))
        {
            if("1".equals(datetime))
            {
                datetime = DateUtils.getCurrentMonth();
            }else if("0".equals(datetime)){
                datetime = DateUtils.getLastMonth();
            }
        }else {
            datetime = DateUtils.getCurrentMonth();
        }

        if (tokenService.compareToken(param.tokenEntity.getValue())){

            HashMap<String,Object> map = townScoreService.queryAfterImport(param.townIndicatorsFilter.getId().toString(),datetime);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME,"token不对",null);



       //townScoreService.importScore(param.townIndicatorsFilter.getTownList(),param.townIndicatorsFilter.getId()).var;
    }

    /**
     * 导出指标完成情况
     * @param reponse
     */
    @GetMapping("/exportExcel")
    public void  exportExcel(HttpServletResponse reponse, String dateTime)
    {


       /* Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age","18");
        try {
            WordUtil.exportWrodFile(reponse,map);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
       // String dateTime = param.townIndicatorsFilter.getDateTime();
        HSSFWorkbook wb= exportExcel.getAllIndiction(dateTime);
        HSSFSheet sheet = wb.getSheetAt(0);
        int rownum = sheet.getLastRowNum();
        if (rownum == 0) {
            throw new SystemException("没有数据");
        }

        OutputStream out = null;
        try {
            out = reponse.getOutputStream();

            String dt = dateTime.substring(0,4)+"年"+"1-"+ Integer.parseInt(dateTime.substring(dateTime.length()-2,dateTime.length()))   +"月";

            String filename =dt+ "乡镇指标完成情况.xls";
            reponse.setContentType("application/x-msdownload");
            reponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            wb.write(out);
        } catch (Exception e) {

        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }


    /**
     * -------指标分析---首页
     * @param param
     * @return
     */
    @PostMapping("/indictionRank")
    public  Result<HashMap<String,Object>> indexRanks(@RequestBody TownScoreParam param)
    {
        String datetime ="";
        if(StringUtils.isBlank(param.townIndicatorsFilter.getDateTime()))
        {
         datetime = DateUtils.getLastMonth();
        }else
        {
            datetime =param.townIndicatorsFilter.getDateTime();
        }

        List<Map<String,Object>> list = townScoreService.queryIndexRank(datetime);
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",list);

        DepartmentFilter defi  = new DepartmentFilter();
        defi.setDepartType("乡镇");
        List<DepartmentFilter> departmentFilters = departmentService.query(defi);
        List<Map<String,String>> listTown = new ArrayList<>();
        for ( DepartmentFilter item :  departmentFilters)
        {
            Map<String,String> townMap = new HashMap<>();
            townMap.put("value",item.getDepartcode());
            townMap.put("label",item.getDepartAddr());
            listTown.add(townMap);

        }
        map.put("townList",listTown);

        return ResultUtils.getSuccessResults(map);
    }

    /**
     * -----------指标分析
     * @param param
     * @return
     */
    @PostMapping("/indictionRank/chart")
    public Result<HashMap<String,Object>> indexRankChart(@RequestBody TownScoreParam param)
    {

        String datetime ="";
        if(StringUtils.isBlank(param.townIndicatorsFilter.getDateTime()))
        {
            datetime = DateUtils.getLastMonth();
            param.townIndicatorsFilter.setDateTime(datetime);
        }
        HashMap<String,Object> map = new HashMap<>();
       /* param.townIndicatorsFilter.setDateTime("201906");
        param.townIndicatorsFilter.setIndexId("1642");*/
      /*  TownIndicatorsFilter filter  = new TownIndicatorsFilter();
        filter.setDateTime("201906");
        filter.setIndexId("1642");*/
        param.townIndicatorsFilter.setIndexId(param.townIndicatorsFilter.getId().toString());
       List<TownIndicatorsFilter> list = townScoreService.getExporScore( param.townIndicatorsFilter);
        List<TownIndicatorsFilter> resultList = new ArrayList<>();
        List<String> names = new ArrayList<>();
        List<String> score = new ArrayList<>();
        List<String> rank = new ArrayList<>();
        List<String> weight = new ArrayList<>();

        //HashMap<String,String> codeToName= townScoreService.getAllDepartmen();

        //指标分析对比接收的乡镇id 默认为空，不过滤，有值就选择过滤值
        List<String> townCode = param.townIndicatorsFilter.getTownListData(); //乡镇code
        if(ObjectUtils.isBlank(townCode))
        {
            resultList = list;
        }else {
            //过滤选中的值
            Map<String, String> collect = townCode.stream().collect(Collectors.toMap(String::toString, Function.identity(), ((s, s2) -> s2)));

            for(TownIndicatorsFilter town: list)
            {
                if(town.getDepartCode().equals(collect.get(town.getDepartCode())))
                {
                    resultList.add(town);
                }


            }

        }


       for(TownIndicatorsFilter item: resultList)
        {
            names.add(item.getTownName());
            score.add(item.getScore());
            rank.add(item.getFinalScore());
            weight.add(item.getWeight());
        }
       map.put("name",names);
       map.put("score",score);
       map.put("finalScore",rank);
       map.put("weight",weight);
       /*
       其他非图表分析
        */
      Map maprank  =  townScoreService.indexAnalyse(param.townIndicatorsFilter.getId(),param.townIndicatorsFilter.getDateTime());
        map.put("others",maprank);
        /*
            乡镇排名
         */
        map.put("rankList",list);

       return  ResultUtils.getResults("200","ok",map);
    }

    /**
       乡镇-指标-分析
     */
    @PostMapping("/townIdex/chart")
    public Result<HashMap<String,Object>> IndexDateReport(@RequestBody TownScoreParam param,HttpServletRequest request)
    {

       DepartmentEntity depart = departmentService.getDepartByName(param.townIndicatorsFilter.getTownName());
        if(ObjectUtils.isBlank(depart))
        {
                  return ResultUtils.getResults("200","ok",new HashMap<>());
        }
        /*
         * 分装数据
         */
         HashMap<String,Object>  map =townScoreService.queryTownIndexValue(param.townIndicatorsFilter.getId().toString(),depart.getDepartcode(),request);
        int code = (int) map.get("code");
        if(code==500)
        {
              return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
        }
        //指标表格数据





       // townScoreService.townAnalyse(depart.getDepartcode(),"2019",null);

        return ResultUtils.getResults("200","ok",map);
    }

    /**
     * ---乡镇分析
     * @param param
     * @return
     */
    @PostMapping("/townIdex/analy")
    public Result<HashMap<String,Object>> townAnaly(@RequestBody TownScoreParam param)
    {
        String townid =param.townFilter.getDepartcode();
        String datetime= param.townFilter.getDatetime();
        int topNum =param.townFilter.getTopNum();
        int badNum = param.townFilter.getBadNum();

        if(StringUtils.isBlank(datetime))
        {
            datetime= DateUtils.getLastMonth();
        }
        String indexId  = param.townFilter.getIndexId();

      HashMap<String,Object> map =  townScoreService.townAnalyse(townid,datetime,null,topNum,badNum);

      return ResultUtils.getSuccessResults(map);
    }


    /**
     * 乡镇指标分析导出word
     */
    @GetMapping("/exportWrod")
    public void  exportword(HttpServletResponse reponse, String  datetime,String townName,String departcode,int topNum ,int badNum){

       /* Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age","18");*/
       if(StringUtils.isBlank(datetime))
       {
           datetime=DateUtils.getCurrentMonth();
       }

        HashMap<String,Object> map =  townScoreService.townAnalyse(departcode,datetime,null,topNum,badNum);
        map.put("datetime",datetime);
        map.put("townName",townName);
        try {
            WordUtil.exportWrodFile(reponse,map,"zbfx.ftl",townName+"指标分析报告.doc");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @PostMapping ("/townhistoryData")
    public Result<HashMap<String,Object>>  historyData(@RequestBody TownScoreParam  param){

        Long id = param.townIndicatorsFilter.getId();
        if(ObjectUtils.isBlank(id))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "指标id不能为空", null);
        }
        List<HistoryScoreDTO> list = townScoreService.TownHistoryData(id);
        HashMap map = new HashMap();
        map.put("list",list);

        return  ResultUtils.getSuccessResults(map);



    }




}
class TownScoreParam{
    public TownIndicatorsFilter townIndicatorsFilter;
    public TownIndicatorsEntity townIndicatorsEntity;
    public TokenEntity tokenEntity;
    public List<TownEntity> townList;
    public TownEntity townEntity;
    public TownFilter townFilter;
    public List<TownIndicatorsFilter> list;
    public TownDTO townDTO;
}


